﻿using System;
using System.Text;

namespace Wikey.Utilities.Extensions
{
   public static class StringExtensions
    {
       public static string UrlFriendlyName( this string @str )
       {
           if (String.IsNullOrEmpty(@str))
               return String.Empty;

           var @newString = @str
                    .Replace(" ", "-")
                    .Replace("/","-")
                    .Replace("&","-")
                    .Replace("'","-")
                    .Replace(@"\","-")
                    ;

           return @newString;
       }

       public static int Int( this string possibleId )
       {
           if (String.IsNullOrEmpty(possibleId))
           {
               return 0;
           }

           int result;

           int.TryParse(possibleId, out result);

           return result; 
               
       }

       public static string UniqueFilename( this string @filename )
       {
           if (String.IsNullOrEmpty(@filename))
           {
               return NewGuid();
           }

           var filenameParts = @filename.Split('.');

           var builder = new StringBuilder();


           for (int idx = 0; idx < filenameParts.Length; idx++)
           {
               if( idx == filenameParts.Length -1 )
               {
                   builder.Append(NewGuid()).Append(".").Append(filenameParts[idx]);
                   break;
               }

               builder.Append(filenameParts[idx]).Append(".");
           }

           return builder.ToString();

       }

       private static string NewGuid()
       {
           return Guid.NewGuid().ToString().Replace("-", String.Empty).Substring(0, 15);
       }

       public static string Hash(this string @password) {

           return BCrypt.HashPassword(@password, BCrypt.GenerateSalt());
       }
    }
}
